package com.zjy.service.impl;

import com.zjy.bean.*;
import com.zjy.dao.*;
import com.zjy.dto.ArticleCondition;
import com.zjy.dto.ArticleParam;
import com.zjy.dto.ArticleResponse;
import com.zjy.dto.ListResponse;
import com.zjy.service.ArticleService;
import com.zjy.utils.ObjectUtils;
import com.zjy.utils.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2019/3/14.
 */
@Service
public class ArticleServiceImpl implements ArticleService{
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private ArticleDetailMapper articleDetailMapper;
    @Resource
    private ArticleCommentMapper articleCommentMapper;
    @Resource
    private ArticleTagRelationMapper articleTagRelationMapper;
    @Resource
    private ArticleTagMapper articleTagMapper;
    @Resource
    private UserCollectionMapper userCollectionMapper;
    @Resource
    private ArticleLikeRelationMapper articleLikeRelationMapper;

    /**
     * 新增博文，同时新增博文详情
     * @param articleParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addArticle(ArticleParam articleParam) {
        Article article = articleParam.getArticle();
        List<String> tagIdList = articleParam.getTagIdList();

        //插入新增文章
        String articleId = UUIDUtils.getUUID();
        article.setId(articleId);
        articleMapper.insertSelective(article);


        //创建并插入文章细节对象
        ArticleDetail articleDetail = new ArticleDetail();
        String articleDetailId = UUIDUtils.getUUID();
        articleDetail.setId(articleDetailId);
        articleDetail.setArticleId(articleId);
        articleDetailMapper.insertSelective(articleDetail);


        //将用户选择的文章标签插入文章标签关系表
        if(!ObjectUtils.isNullOrEmpty(tagIdList) && tagIdList.size() > 0){
            for (String s : tagIdList) {
                ArticleTagRelation articleTagRelation = new ArticleTagRelation();
                articleTagRelation.setId(UUIDUtils.getUUID());
                articleTagRelation.setArticleId(articleId);
                articleTagRelation.setTagId(s);
                articleTagRelationMapper.insertSelective(articleTagRelation);
            }
        }

    }

    /**
     * 删除博文：软删除，把del_flag设为1
     * 同时把文章关联的数据表数据也软删除
     * @param articleId
     * @return 返回受影响(或匹配上但没修改)的行数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteArticleById(String articleId) {
        int count = 0;
        count = articleMapper.deleteArticleById(articleId); //软删除文章表
        articleDetailMapper.deleteArticleDetail(articleId);//软删除文章细节表
        articleTagRelationMapper.deleteArticleTagRelation(articleId);  //软删除文章标签关系表
        articleCommentMapper.deleteArticleComment(articleId);  //软删除文章评论表
        return count;
    }

    /**
     * 更新文章表以及文章相关数据表：只更新非空字段
     * @param articleParam
     * @return 返回受影响(或匹配上但没修改)的行数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateArticleById(ArticleParam articleParam) {
        Article article = articleParam.getArticle();
        List<String> tagIdList = articleParam.getTagIdList();
        String articleId = article.getId();
        int count = 0;
        //更新文章
        count = articleMapper.updateByPrimaryKeySelective(article);

        articleTagRelationMapper.deleteArticleTagRelation(articleId);  //软删除文章标签关系表
        //将用户选择的文章标签插入文章标签关系表
        if(!ObjectUtils.isNullOrEmpty(tagIdList) && tagIdList.size() > 0){
            for (String s : tagIdList) {
                ArticleTagRelation articleTagRelation = new ArticleTagRelation();
                articleTagRelation.setId(UUIDUtils.getUUID());
                articleTagRelation.setArticleId(articleId);
                articleTagRelation.setTagId(s);
                articleTagRelationMapper.insertSelective(articleTagRelation);
            }
        }
        return count;
    }

    /**
     * 根据articleId查找博文
     * @param articleId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ArticleResponse selectArticleById(String userId,String articleId) {
        ArticleResponse articleResponse = new ArticleResponse();
        //根据Id查找文章
        Article article = articleMapper.selectArticleById(articleId);
        if(article != null){
            //设置是否收藏、是否点赞
            UserCollection u = userCollectionMapper.selectByTwoId(userId,articleId);
            if(u != null && u.getDelFlag() == 0){
                article.setIsCollection(1);
            }else {
                article.setIsCollection(0);
            }
            ArticleLikeRelation a = articleLikeRelationMapper.selectByTwoId(userId,articleId);
            if(a != null && a.getDelFlag() == 0){
                article.setIsLike(1);
            }else {
                article.setIsLike(0);
            }
        }
        //根据Id查找文章细节
        ArticleDetail articleDetail = articleDetailMapper.selectArticleDetailByArticleId(articleId);
        //根据Id查找文章标签
        List<ArticleTag> articleTagList = articleTagMapper.selectArticleTagByArticleId(articleId);
        //修改文章浏览数+1
        articleDetailMapper.updateReadNum(articleId,1);

        //把数据装入articleResponse
        articleResponse.setArticle(article);
        articleResponse.setArticleDetail(articleDetail);
        articleResponse.setArticleTagList(articleTagList);
//        articleResponse.setArticleCommentList(articleCommentList);

        return articleResponse;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addLike(String userId, String articleId) {
        //查询是否已存在被删除的点赞关系记录，如已存在则修改del_fla为0，不存在则新插入一条
        ArticleLikeRelation relation = articleLikeRelationMapper.selectByTwoId(userId,articleId);
        if(relation == null){   //找不到则新插入一条
            relation = new ArticleLikeRelation();
            relation.setId(UUIDUtils.getUUID());
            relation.setArticleId(articleId);
            relation.setUserId(userId);
            articleLikeRelationMapper.insertSelective(relation);
        }else if(relation != null && relation.getDelFlag() == 1){
            relation.setDelFlag(0);
            articleLikeRelationMapper.updateByPrimaryKeySelective(relation);
        }
        //修改文章的点赞数+1
        articleDetailMapper.updateLikeNum(articleId,1);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelLike(String userId, String articleId) {
        ArticleLikeRelation relation = articleLikeRelationMapper.selectByTwoId(userId,articleId);
        if(relation != null){
            relation.setDelFlag(1);
            articleLikeRelationMapper.updateByPrimaryKeySelective(relation);
        }
        //修改文章的点赞数-1
        int i= articleDetailMapper.updateLikeNum(articleId,-1);
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ArticleResponse> selectAllArticle() {

        List<ArticleResponse> articleResponseList = new ArrayList<ArticleResponse>();
        //查找所有文章
        List<Article> articleList = articleMapper.selectAllArticle();
        //遍历文章列表，查找文章细节放入ArticleResponse
        if(!ObjectUtils.isNullOrEmpty(articleList)){
            String articleId = null;
            ArticleDetail articleDetail = null;
            for (Article article : articleList) {
                ArticleResponse articleResponse = new ArticleResponse();
                articleId = article.getId();
                articleDetail = articleDetailMapper.selectArticleDetailByArticleId(articleId);
                //根据Id查找文章标签
                List<ArticleTag> articleTagList = articleTagMapper.selectArticleTagByArticleId(articleId);
                articleResponse.setArticle(article);
                articleResponse.setArticleDetail(articleDetail);
                articleResponse.setArticleTagList(articleTagList);
                articleResponseList.add(articleResponse);
            }
        }

        return articleResponseList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ListResponse selectArticleByCondition(ArticleCondition articleCondition) {
        ListResponse response = new ListResponse();
        String userId = articleCondition.getUserId();
        double pageSize = articleCondition.getPageSize(); //获取页面大小
        int totalCount = articleMapper.getArticleCount(articleCondition);  //获取总条数
        int totalPage = 0;
        if(pageSize > 0){
            totalPage = (int)Math.ceil((double)totalCount/pageSize); //计算总页数，结果向上取整
        }

        List<ArticleResponse> articleResponseList = new ArrayList<ArticleResponse>();
        //查找出符合条件的博文
        List<Article> articleList = articleMapper.selectArticleByCondition(articleCondition);

        //遍历博文列表，找出文章详情（点赞数、评价数那些需要显示在文章列表上）
        if(!ObjectUtils.isNullOrEmpty(articleList)){
            for (Article article : articleList) {
                ArticleResponse articleResponse = new ArticleResponse();
                String articleId = article.getId();
                //根据Id查找文章细节
                ArticleDetail articleDetail = articleDetailMapper.selectArticleDetailByArticleId(articleId);
                //根据Id查找文章标签
                List<ArticleTag> articleTagList = articleTagMapper.selectArticleTagByArticleId(articleId);

                if(article != null){
                    article.setText(null);
                    //设置是否收藏、是否点赞
                    UserCollection u = userCollectionMapper.selectByTwoId(userId,articleId);
                    if(u != null && u.getDelFlag() == 0){
                        article.setIsCollection(1);
                    }else {
                        article.setIsCollection(0);
                    }
                    ArticleLikeRelation a = articleLikeRelationMapper.selectByTwoId(userId,articleId);
                    if(a != null && a.getDelFlag() == 0){
                        article.setIsLike(1);
                    }else {
                        article.setIsLike(0);
                    }
                }

                //把数据装入articleResponse
                articleResponse.setArticle(article);
                articleResponse.setArticleDetail(articleDetail);
                articleResponse.setArticleTagList(articleTagList);

                //把articleResponse装入列表
                articleResponseList.add(articleResponse);
            }
        }
        response.setData(articleResponseList);
        response.setPageNum(articleCondition.getPageNum());
        response.setPageSize(articleCondition.getPageSize());
        response.setTotalCount(totalCount);
        response.setTotalPage(totalPage);
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addArticleCollection(UserCollection userCollection) {
        //查询是否存在userId和targetId的关系，若不存在则插入一条，存在则修改del_flag
        UserCollection u = userCollectionMapper.selectByTwoId(userCollection.getUserId(),userCollection.getTargetId());
        if(u == null){
            u = new UserCollection();
            u.setId(UUIDUtils.getUUID());
            u.setTargetType(1);
            u.setUserId(userCollection.getUserId());
            u.setTargetId(userCollection.getTargetId());
            userCollectionMapper.insertSelective(u);
        }else if(u != null && u.getDelFlag() == 1){
            u.setDelFlag(0);
            userCollectionMapper.updateByPrimaryKeySelective(u);
        }
        //修改文章的收藏数+1
        String articleId = userCollection.getTargetId();
        return articleMapper.updateCollectionNum(articleId,1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelArticleCollection(UserCollection userCollection) {
        //软删除用户收藏表
        userCollectionMapper.deleteByTwoId(userCollection.getUserId(),userCollection.getTargetId());
        //修改商品的收藏数-1
        String articleId = userCollection.getTargetId();
        return articleMapper.updateCollectionNum(articleId,-1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Object> getArticleNum() {
        HashMap<String, Object> map = new HashMap<>();
        int todayCount = 0;
        int totalCount = 0;
        //不传入时间则为查询所有用户
        List<Article> allArticleList = articleMapper.selectArticleList("","");
        if(allArticleList != null){
            totalCount = allArticleList.size();
        }
        Date date = new Date(); //获取当前的系统时间。
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");//今天零点
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//当前时间
        String begin = dateFormat1.format(date) + " 00:00:00";
        String now = dateFormat2.format(date);
        //不传入时间则为查询所有用户
        List<Article> todayArticleList = articleMapper.selectArticleList(begin,now);
        if(todayArticleList != null){
            todayCount = todayArticleList.size();
        }
        map.put("totalCount",totalCount);
        map.put("todayCount",todayCount);
        return map;
    }

}
